package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;

public class GamerlolNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {

		if (url.startsWith("http://pic.gamerlol.com")){
			return false;
		}
		String[] regex={ 
							"http://.*.gamerlol.com/.*[0-9]{4}/[0-9]{1,2}/news_[0-9]+_[0-9]+.shtml",
							"http://.*.gamerlol.com/.*[0-9]{5}/news_[0-9]+_[0-9]+.shtml"
							};
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		String html=urlMeta.getHtml();
		if (html == null) {
		}
		String title="";
		String content="";
		Long date=0l;
		int commentNum=0;
		int clickNum=0;
		NewsMeta meta=new NewsMeta();
		meta.setUrl(url);
		meta.setType(0);
		Document doc=Jsoup.parse(html);
		urlMeta=null;
		/*
		 * 解析新闻标题
		 */
		title=doc.select("h1").text();
		/*
		 * 解析时间
		 */
		date=DateUtils.matchDate(doc.select("h2,h3").text());
		if (date==null){
			date=DateUtils.matchDate(doc.select(":containsOwn(发布时间：)").text());
		}
		/*
		 * 解析内容
		 */
		content=HtmlCleaner.getContentHtml(url,doc.select("div#neirong"));

		/**
		 * 初始化、截取 、设置作者信息*******************************************
		 * 
		 * */
//		String author=null;
//		author=doc.select("").text();
//		author=StringUtils.substringBetween(author, "来源："," ");
//		meta.setAuthor(author);
		/**
		 *                        	 **************************end *************************
		 * 
		 **/
		
		if (StringUtils.isBlank(content)) {
			content=HtmlCleaner.getContentHtml(url,doc.select("div.zjd_news p"));			
			if (StringUtils.isBlank(content)) {
				content=HtmlCleaner.getContentHtml(url,doc.select("table.web"));			
			}
		}
		if (StringUtils.isBlank(title)) {
		}
		meta.setTitle(title);
		meta.setContent(content);
		meta.setDate(date);
		meta.setClickNum(clickNum);
		meta.setCommentNum(commentNum);

		return meta;
	}


	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	public static void main(String[] args) {
		String url="http://psp.gamerlol.com/2012/10/news_23364_4042.shtml";
		UrlMeta urlMeta=CrawlHTML.responseToURL(url);
		GamerlolNewsAnalyse a=new GamerlolNewsAnalyse();
		boolean detailPage=a.isDetailPage(url);
		if (detailPage) {
			NewsMeta parserHtml=a.parserHtml(urlMeta);
			System.out.println(parserHtml);
		} else {
			System.out.println("不符合正则");
		}

	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
